package cn.jingyuan.swan.cloud.web;

import cn.jingyuan.bee.enums.spring.convert.EnumIntegerConverter;
import cn.jingyuan.bee.enums.spring.convert.EnumStringConverter;
import cn.jingyuan.bee.fastjson.BeeParserConfig;
import cn.jingyuan.bee.fastjson.BeeSerializeConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


public class DefaultWebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter jsonConverter = fastJsonHttpMessageConverter();
        converters.add(0, jsonConverter);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new EnumStringConverter());
        registry.addConverterFactory(new EnumIntegerConverter());
    }

    private static FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        SerializeConfig serializeCfg = BeeSerializeConfig.globalInstance;

        // Long 序列化为 String
        serializeCfg.put(Long.class, ToStringSerializer.instance);
        serializeCfg.put(Long.TYPE, ToStringSerializer.instance);

        // Double 序列化为 String
        serializeCfg.put(Double.class, ToStringSerializer.instance);
        serializeCfg.put(Double.TYPE, ToStringSerializer.instance);

        // Float 序列化为 String
        serializeCfg.put(Float.class, ToStringSerializer.instance);
        serializeCfg.put(Float.TYPE, ToStringSerializer.instance);

        // BigDecimal 序列化为 String
        serializeCfg.put(BigDecimal.class, ToStringSerializer.instance);

        // 注册自定义序列化
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);

        config.setSerializeConfig(serializeCfg);
        config.setParserConfig(BeeParserConfig.global);


        // 处理中文乱码问题(不然出现中文乱码)
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);

        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        converter.setFastJsonConfig(config);
        converter.setSupportedMediaTypes(fastMediaTypes);

        return converter;
    }

}
